using DimensionsHelper.LanguageService.Symbols;
using DimensionsHelper.LanguageService.Syntax;

namespace DimensionsHelper.LanguageService;

/// <summary>
///     语法分析树字符串节点。
/// </summary>
public class AnalysisString : AnalysisExpression
{
    internal AnalysisString(StringLiteral syntaxNode, AnalysisNode? parent) :
        base(AnalysisBoundKinds.Literal, syntaxNode, parent)
    {
        Syntax = syntaxNode;
        Bind(ValueTypeSymbol.String);
    }


    public override StringLiteral Syntax { get; }

    public string Value => Syntax.Value;


    public override AnalysisExpression? WithImplicitlyConversion(ValueTypeSymbol targetType)
    {
        if (targetType == ValueTypeSymbol.String || targetType == ValueTypeSymbol.Any)
        {
            return this;
        }

        if (targetType == ValueTypeSymbol.Boolean)
        {
            return NodeConverter.TryConvertToBoolean(Syntax, out BooleanLiteral? booleanLiteral)
                ? new AnalysisBoolean(booleanLiteral, Parent)
                : null;
        }

        if (targetType == ValueTypeSymbol.Long)
        {
            return NodeConverter.TryConvertToInteger(Syntax, out IntegerLiteral? integerLiteral)
                ? AnalysisNodeFactory.Integer(integerLiteral, Parent)
                : null;
        }

        if (targetType == ValueTypeSymbol.Double)
        {
            return NodeConverter.TryConvertToDouble(Syntax, out DoubleLiteral? doubleLiteral)
                ? AnalysisNodeFactory.Double(doubleLiteral, Parent)
                : null;
        }

        if (targetType == ValueTypeSymbol.Categorical)
        {
            return NodeConverter.TryConvertToCategorical(Syntax, out CategoricalLiteral? categoricalLiteral)
                ? AnalysisNodeFactory.Categorical(categoricalLiteral, Parent)
                : null;
        }

        if (targetType == ValueTypeSymbol.Date && DateTime.TryParse(Syntax.Value, out DateTime dateLiteral))
        {
            return AnalysisNodeFactory.Date(Syntax, dateLiteral, Parent);
        }

        return null;
    }

    public override IEnumerable<AnalysisNode> GetChildren()
    {
        return [];
    }

    internal override void AddChild(AnalysisNode child)
    {
        throw new NotSupportedException("AnalysisString cannot have children.");
    }
}

public static partial class AnalysisNodeFactory
{
    /// <summary>
    ///     创建一个字符串节点
    /// </summary>
    /// <param name="syntaxNode">原始语法节点</param>
    /// <param name="parent">父节点，可以忽略</param>
    /// <returns></returns>
    public static AnalysisString String(StringLiteral syntaxNode, AnalysisNode? parent)
    {
        return new AnalysisString(syntaxNode, parent);
    }
}